﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class Joystick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{

    public Vector3 normalCenter;
    public static float joystickH;
    public static float joystickV;

    private bool isDrag;
    private Vector3 startPos;
    private Vector3 dragPos;


    void Awake()
    {
        isDrag = false;
        startPos = transform.localPosition;
    }

    void Update()
    {
        if (isDrag)
        {
            float distance = Vector3.Distance(dragPos, normalCenter);
            Vector3 dirNormal = dragPos - normalCenter;
            if (distance > 45)
            {
                transform.localPosition = dirNormal.normalized * 50;
            }
            else
            {
                transform.localPosition = dirNormal;
            }
            joystickH = dirNormal.x / 1000;
            joystickV = dirNormal.y / 1000;
        }
        else
        {
            transform.localPosition = startPos;
            joystickH = 0;
            joystickV = 0;
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
    }

    public void OnDrag(PointerEventData eventData)
    {
        dragPos = eventData.position;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        isDrag = false;
    }
}